<template>
  <page-header-wrapper :title="false">
    <a-card title="账户详情">
      <template #extra> <a-button type="primary" @click="handleEdit(detail)">编辑账户</a-button></template>
      <a-descriptions bordered title="" size="small">
        <a-descriptions-item label="账户名" :span="3"> {{ detail.accountName }} </a-descriptions-item>
        <a-descriptions-item label="联系电话" :span="3"> {{ detail.phone }}</a-descriptions-item>
        <a-descriptions-item label="创建日期" :span="3"> {{ detail.updateTime }}</a-descriptions-item>
        <a-descriptions-item label="初始金额" :span="3"> {{ detail.startAmount ?? 0 }}元 </a-descriptions-item>
        <a-descriptions-item label="当前结余" :span="3"> {{ detail.debtAmount ?? 0 }}元 </a-descriptions-item>
        <a-descriptions-item label="状态" :span="3">
          <a-tag color="#82af6f" v-if="detail.status == 1">可欠账</a-tag>
          <a-tag color="#abbac3" v-else>已停用</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="备注" :span="3"> {{ detail.memo }} </a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card title="账户流水记录" style="margin-top: 24px">
      <template #extra> <a-button type="primary" @click="handleTurnCreate()">新增债务</a-button></template>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="筛选">
                <a-input v-model="queryParam.queryCondition" allow-clear placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="日期">
                <a-range-picker v-model="queryParam.date" format="YYYY-MM-DD" />
              </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" :loading="loading" @click="handleSearch(queryParam)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <a-table
        ref="table"
        size="default"
        rowKey="key"
        :pagination="pagination"
        @change="handleTableChange"
        :columns="columns"
        :data-source="loadData"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="types" slot-scope="text,record">
          <template>
            <div v-if="record.types == '0'">销售收入</div>
            <div v-if="record.types == '1'">销售欠账</div>
            <div v-if="record.types == '2'">转出</div>
            <div v-if="record.types == '3'">转入</div>
            <div v-if="record.types == '4'">新增支出</div>
            <div v-if="record.types == '5'">新增收入</div>
            <div v-if="record.types == '6'">收预付款</div>
            <div v-if="record.types == '7'">退预付款</div>
            <div v-if="record.types == '8'">欠账</div>
            <div v-if="record.types == '9'">清账</div>
            <div v-if="record.types == '10'">借钱</div>
            <div v-if="record.types == '11'">还钱</div>
            <div v-if="record.types == '12'">入股</div>
            <div v-if="record.types == '13'">退股</div>
            <div v-if="record.types == '14'">分红</div>
            <div v-if="record.types == '15'">收取押金</div>
            <div v-if="record.types == '16'">缴纳押金</div>
          </template>
        </span>
        <span slot="checkStatus" slot-scope="text,record">
          <template>
            <a-tag color="#82af6f" v-if="record?.checkStatus == 1">已审核</a-tag>
            <a-tag color="#D15B47" v-else>待审核</a-tag>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#428bca" @click="handleDetail(record)">进入</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
    <turn-form
      ref="turnModal"
      :visible="turnVisible"
      :loading="turnConfirmLoading"
      :model="turnMdl"
      @cancel="handleTurnCancel"
      @ok="handleTurnOk"
    />
  </page-header-wrapper>
</template>

<script>
import { getDebtUsingGET,addDebtRecordUsingPOST, updateDebtUsingPOST,getStAcclogListUsingGET } from '@/api/api/qiantaizhangwu.ts'
import CreateForm from './CreateForm'
import TurnForm from './TurnForm'
import moment from 'moment'
import { omit } from 'lodash-es'
export default {
  name: 'CashierAccountDetail',
  components: {
    CreateForm,
    TurnForm,
  },
  data() {
    return {
      mdl: null,
      visible: false,
      confirmLoading: false,
      turnMdl: null,
      turnVisible: false,
      turnConfirmLoading: false,
      pagination: {
        total: 0,
      },
      loading: false,
      queryParam: {
        pageNo: 1,
        pageSize: 10,
        queryCondition: '',
        date: [ moment().startOf('months').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD') ],
        status: '',
      },
      detail: {},
      advanced: false,
      columns: [
        {
          title: '日期',
          dataIndex: 'date',
        },
        {
          title: '类型',
          dataIndex: 'types',
          scopedSlots: { customRender: 'types' },
        },
        {
          title: '金额(元)',
          dataIndex: 'amount',
        },
        {
          title: '余额(元)',
          dataIndex: 'balance',
        },
        {
          title: '记账人',
          dataIndex: 'empName',
        },
        {
          title: '审核状态',
          dataIndex: 'checkStatus',
          scopedSlots: { customRender: 'checkStatus' },
        },
        {
          title: '备注',
          dataIndex: 'memo',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '180px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      loadData: [],
    }
  },
  mounted() {
    this.getDetail()
    this.handleSearch(this.queryParam)
  },
  methods: {
    handleDetail(record) {
      this.$router.push({ path: `/cashier/debt/order/${record.orderId}` })
    },
    getDetail() {
      getDebtUsingGET({ id: this.$route.params.id })
        .then((res) => {
          this.detail = res.data
        })
        .catch(() => {
          this.$message.error('获取详情失败,请联系管理员')
        })
    },
    handleSearch(val) {
      this.loading = true
      const params = {
        ...val,
        accId: this.$route.params.id,
        startTime: val?.date?.[0] ? moment(val?.date?.[0]).format('YYYY-MM-DD') : null,
        endTime: val?.date?.[1] ? moment(val?.date?.[1]).format('YYYY-MM-DD') : null,
      }
      getStAcclogListUsingGET({ ...omit(params, ['date'])})
        .then((res) => {
          this.loadData = res.data.list
          this.loading = false
          this.queryParam.pageNo = this.pagination.current
          this.pagination = { ...this.pagination, total: Number(res.data.total) }
        })
        .catch((error) => {
          this.loading = false
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
 pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        queryCondition:this.queryParam.queryCondition,
        status:this.queryParam.status,
        date:this.queryParam.date
      })
    },
    handleEdit(record) {
      this.mdl = { ...record }
      this.visible = true
    },
    handleOk() {
      this.visible = false
      this.confirmLoading = true
      const form = this.$refs.createModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          updateDebtUsingPOST({ ...values })
            .then(() => {
              this.getDetail()
              this.$message.success('修改成功')
            })
            .catch(() => {
              this.$message.error('修改失败,请联系管理员')
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleTurnCreate() {
      this.turnMdl = {}
      this.turnVisible = true
    },
    handleTurnOk() {
      this.turnConfirmLoading = true
      const form1 = this.$refs.turnModal.form
      form1.validateFields((errors, values) => {
        if (!errors) {
          addDebtRecordUsingPOST({accId:this.$route.params.id, ...values,date:values.date })
            .then(() => {
              this.handleSearch(this.queryParam)
              this.turnVisible = false
              this.turnConfirmLoading = false
              this.$message.success('操作成功')
            })
            .catch((error) => {
              this.turnConfirmLoading = false
              that.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        } else {
          this.turnConfirmLoading = false
        }
      })
    },
    handleTurnCancel() {
      this.turnVisible = false
      const form = this.$refs.turnModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
  },
}
</script>
